package net_TCP.GQ;

//import java.io.IOException;
//import java.io.InputStream;
//import java.io.OutputStream;
//import java.io.PrintWriter;
//import java.net.ServerSocket;
//import java.net.Socket;
import java.io.*;
import java.net.*;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;
import java.util.concurrent.*;
import java.util.*;

public class TCPServer {
    private ServerSocket serverSocket=null;
    public TCPServer(int port) throws IOException{
        serverSocket=new ServerSocket(port);
    }
    public void start() throws IOException{
        ExecutorService executor=Executors.newCachedThreadPool();
        while (true){
            Socket clientSocket= serverSocket.accept();
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    try{
                        processConnect(clientSocket);
                    }catch (IOException e){
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }
    public void processConnect(Socket socket) throws IOException{
        try(InputStream inputStream=socket.getInputStream();
            OutputStream outputStream=socket.getOutputStream()){
            while(true) {
                System.out.printf("客户端链接：[%s,%d]", socket.getInetAddress().toString(), socket.getPort());
                //1.从客户端读取数据
                Scanner reqScanner=new Scanner(inputStream);
                if(!reqScanner.hasNext()){
                    System.out.printf("客户端关闭：[%s,%d]",socket.getInetAddress().toString(),socket.getPort());
                    break;
                }
                String request=reqScanner.next();
                //2.处理请求
                String response=process(request);
                //3.返回响应
                PrintWriter printWriter=new PrintWriter(outputStream);
                printWriter.println(response);
                printWriter.flush();
                //4.打印
                System.out.printf("[%s,%d],req:%s,resp:%s",socket.getInetAddress().toString(),socket.getPort(),request,response);
            }
        }catch(IOException e){
            throw new RuntimeException();
        }finally {
            serverSocket.close();
        }
    }
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TCPServer tcpServer=new TCPServer(9090);
        tcpServer.start();
    }
}
